package com.tian.excel.controller;

import com.alibaba.excel.EasyExcel;
import com.tian.excel.entity.UserInfo;
import com.tian.excel.listener.DemoDataListener;
import com.tian.excel.mapper.UserInfoDao;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Controller;
import org.springframework.web.bind.annotation.GetMapping;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletResponse;
import java.io.IOException;
import java.net.URLEncoder;
import java.util.ArrayList;
import java.util.List;

/**
 * @author: Tian
 * @version: 1.0
 * @since: 1.0
 * @date: 2024/7/20/15:13
 */
@RestController
public class ExelController {

    private UserInfoDao userInfoDao=new UserInfoDao() {
        @Override
        public int saveBatch(List<UserInfo> list) {
            System.out.println(list);
            return 1;
        }
    };
    @GetMapping("download")
    public void download(HttpServletResponse response) throws IOException {
        List<UserInfo> data=new ArrayList<>();
        data.add(new UserInfo(1,"run",23,"封丘"));
        data.add(new UserInfo(2,"tian",23,"长垣"));
        response.setContentType("application/vnd.openxmlformats-officedocument.spreadsheetml.sheet");
        response.setCharacterEncoding("utf-8");
        // 这里URLEncoder.encode可以防止中文乱码 当然和easyexcel没有关系
        String fileName = URLEncoder.encode("测试", "UTF-8").replaceAll("\\+", "%20");
        response.setHeader("Content-disposition", "attachment;filename*=utf-8''" + fileName + ".xlsx");
        EasyExcel.write(response.getOutputStream(), UserInfo.class).sheet("模板").doWrite(data);
    }

    @PostMapping("upload")
    public String upload(MultipartFile file) throws IOException {
        EasyExcel.read(file.getInputStream(), UserInfo.class, new DemoDataListener(userInfoDao)).sheet().doRead();
        return "success";
    }

}
